package br.ufc.parser;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

import br.ufc.histogram.Histogram;
import net.sf.jsqlparser.*;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;

public class SQLParser {

	CCJSqlParserManager parserManager = new CCJSqlParserManager();

	public SQLParser() throws JSQLParserException
	{

	}

	public HashMap<String, String> returnWhere(String statement) throws JSQLParserException{
		PlainSelect plainSelect = (PlainSelect) ((Select) parserManager.parse(new StringReader(statement))).getSelectBody(); 
		
		String[] where = plainSelect.getWhere().toString().replace(" ", "").split("AND|OR");
		HashMap<String, String> attValue = new HashMap<String, String>();
		
		for (int i = 0; i < where.length; i++) {
			attValue.put(where[i].split("=")[1], where[i].replace("'", "").split("=")[2]);
		}
		
		return attValue;
	}
	
	public Collection<Predicate> getPredicates(String statement){
		ArrayList<Predicate> predicates = new ArrayList<Predicate>();
		
		PlainSelect plainSelect;
		try {
			plainSelect = (PlainSelect) ((Select) parserManager.parse(new StringReader(statement))).getSelectBody();
		} catch (JSQLParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
//		String[] where = plainSelect.getWhere().toString().replace(" ", "").split("AND|OR");
		
//		System.out.println(plainSelect.getWhere().toString());
		
//		for (int i = 0; i < where.length; i++) {
//			attValue.put(where[i].split("=")[1], where[i].replace("'", "").split("=")[2]);
//		}
		
//		return attValue;
		
		return null;
		
		
	}
	
	public static void main(String[] args) throws JSQLParserException, IOException
	{
		Histogram h = new Histogram("user_id", "/home/toni/Dropbox/UFC/projetoJavam_2013.2/10.101.10.52log612468322864135.csv");
		h.build();
		h.printHistogram();
		h.sort();
		System.out.println();
		h.printHistogram();
		
	}

}
